'use strict';


import axios from 'axios'
import router from "../router";
// import { getToken, setToken,settingToken,removeToken} from "../utils/auth";
import tool from '@/utils/tool';
import {ElNotification, ElMessageBox,Message} from 'element-plus';
// import store from '@/store'
const service = axios.create({
	// baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
	timeout: 30000 // request timeout
})

const options = {
	text: '加载中',
	background: 'rgba(0, 0, 0, 0.4)',
	spinner: 'el-icon-loading',
	lock: true,
	target: '#app'
};
let loadingInstance;

let elMsg = null;
// request interceptor
service.interceptors.request.use(
	config => {
		if(loadingInstance) {loadingInstance.close();}
		
		if(config.isLoading){loadingInstance = Loading.service(options);}

		// if (config.url.startsWith('/fengyun')){config.baseURL = '';}else{config.baseURL = '/log/';}
		if (tool.cookie.get("TOKEN")) {
				// config.headers.Authorization = `Bearer ${getToken('dapCookie')}`;
				config.headers.Authorization = `Bearer ${tool.cookie.get("TOKEN")}`;
		}

		// console.log(config.url)
		if (config.url == '/login') {
			config.headers = {"Content-Type": "application/x-www-form-urlencoded",}
		} else if (config.url == '/terracewatch/watch/uploadFile' || config.url == '/copyright/upload') {
			config.headers = {'Content-Type': 'multipart/form-data'}
		} else {
			config.headers = {
				"Content-Type": "application/json",
			}
		}

		var extra={};//扩展的参数
		// if(config.extra){ extra=config.extra; delete config.extra; }
		if(extra.formdata){//formdata形式的post请求
			config.headers={
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			}
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		if(response.headers.code){settingToken('headersCode',response.headers.code)};
		if(loadingInstance){loadingInstance.close();}
		
		
		
		//判断是否超时
		let flag = response.headers['session-status']
		if (flag == "timeout") {
			//拦截提示在 Login.vue 登录页的 created 生命周期中处理
			
			return false
		}
		const res = response.data;
		if(loadingInstance){loadingInstance.close();}
		if (res.responseCode == 1) {
			elMsg && elMsg.close()
      elMsg = Message({message: res.message || res.msg || 'Error',type: 'info',duration: 2 * 1000});
			return Promise.reject(new Error(res.message || res.msg || 'Error'))
		} else if (res.responseCode == 401 || res.code == 401) {
			// elMsg && elMsg.close()
      // elMsg = Message({message: res.message || res.msg || 'Error',type: 'info',duration: 2 * 1000});
			// return false
		} else if (res.responseCode == 506) {
			router.push('/licence/index?msg=506');
			// return false;
		}else if (res.responseCode == 412){
			router.push('/licence/index?msg=412');
		}else if(res.responseCode==500 || res.status==500){
			elMsg && elMsg.close()
      elMsg = Message({message: res.message || res.msg || 'Error',type: 'info',duration: 2 * 1000});
			return Promise.reject(new Error(res.message || res.msg || 'Error'))
		}else if(res.responseCode==402){
			elMsg && elMsg.close()
      elMsg = Message({message: res.message || res.msg || 'Error',type: 'info',duration: 2 * 1000});
		}else{
			return res
		}
	},
	function(error) {
		if (error.message != '取消请求') {}
		if (error && error.response && error.response.status) {
			if (error.response.status === 500 || error.response.status === -3) {
				elMsg && elMsg.close()
      	elMsg = Message({message: res.message || res.msg || 'Error',type: 'info',duration: 2 * 1000});
				// router.push('/login?msg=401');
			}
		}
		if(loadingInstance){loadingInstance.close();}
		return Promise.reject(error)
	}
);





let interceptorApi={
	reqSuccess(config){
		const TOKEN=sessionStorage.getItem('TOKEN');
		if(TOKEN){ config.headers['X-Access-Token']=TOKEN; }

		var extra={};//扩展的参数
		if(config.extra){
			extra=config.extra;
			delete config.extra;
		}

		if(extra.isLoading){//显示全局整屏loading
			loadingInstance = Loading.service(loadingOption);
		}

		if(extra.formdata){//formdata形式的post请求
			config.headers={
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'X-Requested-With': 'XMLHttpRequest'
			}
		}

		return config;
	},
	reqFail(error){
		if(loadingInstance){
			loadingInstance.close();
			loadingInstance=null;
		}
		return Promise.reject(error);
	},

	resSuccess(response){

		if(loadingInstance){//关闭loading
			loadingInstance.close();
			loadingInstance=null;
		}
		//数据处理
		var showClose=true;
		var data=response.data, code=data.code || data.success;
		if(code && ![200,0].includes(code)){
			let message=data.message || data.msg;
			switch(code){
				case 1: case 500: case 402:
					elMsg && elMsg.close()
      		elMsg = Message({showClose, message, type: 'info'}); 
					break;
				case 401:
					elMsg && elMsg.close()
      		elMsg = Message({showClose, message, type: 'info'}); 
					console.log(23423424234)
					router.push('/login?msg=401'); break;
				case 506: case 412:
					router.push('/licence/index?msg='+code); break;
				default : 
					elMsg && elMsg.close()
					elMsg = Message({showClose, message, type: 'info'});
			}
		}

		return data;
	},
	resFail(error){
		//关闭loading
		if(loadingInstance){
			loadingInstance.close();
			loadingInstance=null;
		}
	
		//异常处理
		var showClose=true;
		if(error.response){
			var url=error.config.url;
			var res=error.response;
			var data=res.data;
			console.log('------请求异常响应结果------',res);
			
			elMsg && elMsg.close()
      elMsg = Message({showClose, message: data.message || res.statusText || '请求异常', type: 'error'});
	
			return Promise.reject(res);
		}else{//取消的请求会走这
			elMsg && elMsg.close()
      elMsg = Message({showClose, message: error.message , type: 'info'});
		}
	}
}

let http1=axios.create({
	baseURL: process.env.VUE_APP_BASE_NEWURL, 
	timeout: 30000 
});
//请求前的拦截
http1.interceptors.request.use(interceptorApi.reqSuccess,interceptorApi.reqFail);
//响应拦截
http1.interceptors.response.use(interceptorApi.resSuccess,interceptorApi.resFail);

let http2=axios.create({
	baseURL:'/py/', timeout:30000
});
//请求前的拦截
http2.interceptors.request.use(interceptorApi.reqSuccess,interceptorApi.reqFail);
//响应拦截
http2.interceptors.response.use(interceptorApi.resSuccess,interceptorApi.resFail);



export {http1,http2};

export default service







